package com.leyou.item.controller;


import com.leyou.item.entity.Category;
import com.leyou.item.service.CategoryService;
import com.leyou.item.dto.CategoryDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    /**
     * 根据分类id，查询商品分类
     * @return
     */
    @GetMapping("/{id}")
    public ResponseEntity<CategoryDTO> queryCategoryById(@PathVariable("id") Long id){
        Category category = categoryService.getById(id);
        //这里需要转DTO
        CategoryDTO categoryById = new CategoryDTO(category);
        return ResponseEntity.ok(categoryById);

    }

    /**
     *根据分类id的集合，查询商品分类的集合
     */
    @GetMapping("/list")
    public ResponseEntity<List<CategoryDTO>> queryCategoryByIds(@RequestParam("ids") List<Long> ids){

       //根据id批量查询
        List<Category> categoryList=categoryService.listByIds(ids);
//        List<CategoryDTO> list = new ArrayList<>();
//        for (Category category : categoryList) {
//            list.add(new CategoryDTO(category));
//        }
//        return ResponseEntity.ok().body(list);

        List<CategoryDTO> dtoList = categoryList.stream()
//                .map(category -> new CategoryDTO(category))
                .map(CategoryDTO::new)
                .collect(Collectors.toList());
        return ResponseEntity.ok(dtoList);

    }

    /**
     * 根据父类目，查询子分类
     */

    @GetMapping("/of/parent")
    public ResponseEntity<List<CategoryDTO>> queryCategoryByParentId(@RequestParam("pid") Long pid) {
//        List<Category> categoryList = categoryService.query().eq("parent_id", pid).list();
//        List<CategoryDTO> dtoList = CategoryDTO.convertEntityList(categoryList);
//        return ResponseEntity.ok(dtoList);
//        return ResponseEntity.ok(CategoryDTO.convertEntityList
//                (categoryService.query().eq("parent_id", pid).list()));
        List<Category> categoryList = categoryService.query().eq("parent_id", pid).list();
        List<CategoryDTO> dtos = categoryList.stream().map(CategoryDTO::new).collect(Collectors.toList());
        return ResponseEntity.ok(dtos);


    }

    /**
     * 根据品牌id，查询商品分类的集合
     */

    @GetMapping("/of/brand")
    public ResponseEntity<List<CategoryDTO>> queryCategoryByBrandId(@RequestParam("id") Long brandId){

        List<CategoryDTO> doList = categoryService.queryCategoryByBrandId(brandId);

        return ResponseEntity.ok(doList);

    }
}
